package com.upc.feedish;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowInsetsController;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.upc.feedish.ui.dashboard.DashboardFragment;
import com.upc.feedish.ui.home.HomeFragment;
import com.upc.feedish.ui.locate.LocateFragment;
import com.upc.feedish.ui.notifications.NotificationsFragment;
import com.upc.feedish.ui.user.UserFragment;
import com.upc.feedish.utils.DataBaseController;
import com.upc.feedish.utils.MyBroadcastReceiver;
import com.upc.feedish.utils.MyTools;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.viewpager.widget.ViewPager;

import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS;


public class BarActivity extends AppCompatActivity {
    public String token;
    private ViewPager viewPager;// 视图翻页工具
    private HomeFragment homeFragmentPage = new HomeFragment();
    private DashboardFragment dashboardFragment = new DashboardFragment();
    private NotificationsFragment notificationsFragment = new NotificationsFragment();
    private UserFragment userFragment = new UserFragment();
    private LocateFragment locateFragment = new LocateFragment();
    private BottomNavigationView navView;
    private DataBaseController dataBaseController;
    MyBroadcastReceiver br;

    NotificationCompat.Builder builder;
    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBaseController=new DataBaseController();
        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
        token= sp.getString("token","");
        if (token.equals("")){
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }else{
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(dataBaseController.isExpired(token)){
                        startActivity(new Intent(BarActivity.this,MainActivity.class));
                        finish();
                    }
                }
            }).start();
        }
        br=new MyBroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                super.onReceive(context, intent);
                if(intent.getStringExtra("ifLightOn").equals("ON")){
                    showNotification("光照强度过低！");
                }
                if(intent.getStringExtra("ifMotorOn").equals("ON")){
                    showNotification("温湿度超标！");
                }
                if(intent.getStringExtra("personWarning").equals("ON")){
                    showNotification("有人进入！");
                }

            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.upc.learning.HUAWEI");
        registerReceiver(br, intentFilter);
        //通知////////////////////////////////////
//        Intent intent = new Intent(this, BarActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//
//        builder = new NotificationCompat.Builder(this, "my_channel_01")
//                .setSmallIcon(R.drawable.toss)
//                .setContentTitle("您的智能管家提醒您：")
//                .setContentText("温湿度超标！")
//                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
//                .setContentIntent(pendingIntent)
//                .setAutoCancel(true);
        //通知////////////////////////////////////

        setContentView(R.layout.activity_bar);
        navView = findViewById(R.id.nav_view);
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_bar);
//        NavigationUI.setupWithNavController(navView, navController);
        initView();
        /*                                将状态栏设为透明                                      */
//        WindowInsetsController wic = getWindow().getInsetsController();
//        wic.setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS,APPEARANCE_LIGHT_STATUS_BARS);
//        getWindow().setStatusBarColor(APPEARANCE_LIGHT_STATUS_BARS);
        /*                                 将状态栏设为透明                                    */
    }



    public void initView(){
        viewPager = findViewById(R.id.viewPager);
        // 监听viewPager页面变化事件
        viewPager.addOnPageChangeListener(viewPagerListener);
        // 获取Fragment管理对象
        FragmentManager fragmentManager = getSupportFragmentManager();
        // FragmentPagerAdapter 来处理多个 Fragment 页面
        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(fragmentManager) {
            @Override
            public Fragment getItem(int position) {
                switch (position){
                    case 0:
                        return homeFragmentPage;
                    case 1:
                        return locateFragment;
                    case 2:
                        return dashboardFragment;
                    case 3:
                        return userFragment;
                }
                return null;
            }

            @Override
            public int getCount() {
                return 4;
            }
        };
        // viewPager 设置 adapter
        viewPager.setAdapter(fragmentPagerAdapter);
        // navigationView点击事件
        navView.setOnNavigationItemSelectedListener(navigationViewListener);

    }


    /**
     * 监听ViewPager页面变化事件
     * */
    ViewPager.OnPageChangeListener viewPagerListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position,float positionOffset,int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            navView.getMenu().getItem(position).setChecked(true);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    /**
     * 监听BottomNavigationView点击事件
     * */
    BottomNavigationView.OnNavigationItemSelectedListener navigationViewListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            // menu文件夹中bottom_nav_menu.xml里加的android:orderInCategory属性就是下面item.getOrder()取的值
            viewPager.setCurrentItem(menuItem.getOrder());
            return true;
        }
    };

    public void toManage(View v){
        Intent intent = new Intent(BarActivity.this,ManageActivity.class);
        startActivity(intent);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        unregisterReceiver(br);
    }

    public void showNotification(String s){
        Intent intent = new Intent(this, BarActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(BarActivity.this,0,intent,0);

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT >= 26)
        {
            //当sdk版本大于26
            String id = "channel_1";
            String description = "报警提醒";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(id, description, importance);
            channel.enableLights(true);
            channel.enableVibration(true);
            channel.setVibrationPattern( new long[]{100, 100, 200} );
            channel.shouldShowLights();

            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(BarActivity.this, id)
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(R.drawable.toss)
                    .setContentTitle("您的智能管家提醒您：")
                    .setContentText(s)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .build();
            manager.notify(1, notification);
        }
        else
        {
            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(BarActivity.this)
                    .setContentTitle("您的智能管家提醒您：")
                    .setContentText(s)
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
            manager.notify(1,notification);
        }
    }


}